package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @Autowired(required = false)
    private HttpSession session;

    //添加购物车业务
    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart){
        //1.接收请求数据封装到ShoppingCart对象中
        //2.获取登录数据用户的id封装到ShoppingCart对象中
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);
        //3.调用业务层添加购物车
        ShoppingCart shoppingCartNew = shoppingCartService.addCart(shoppingCart);

        //4.设置返回数据,将购物车对象返回
        return R.success(shoppingCartNew);
    }

    //查询指定用户的购物车集合数据
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findByUserId(){
        //1.获取登录的用户id
        Long userId = (Long) session.getAttribute("user");

        //2.调用业务层获取指定用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartService.findAllByUserId(userId);

        //3.返回数据
        return R.success(shoppingCartList);
    }

    //删除指定用户的购物车(清空购物车)
    @RequestMapping("/clean")
    public R<String> clean(){
        //1.获取登录用户id
        Long userId = (Long) session.getAttribute("user");

        //2.调用业务层删除
        shoppingCartService.clean(userId);

        //3.返回数据
        return R.success("清空购物车成功");
    }
}
